package com.jwgf.mqtt.mqttactions;

import com.alibaba.fastjson.JSONObject;
import com.jwgf.group.GroupMap;
import com.jwgf.mqtt.MqttAction;
import com.jwgf.smarowindingmachine_unity.logic.MachineParameterSharedPreference;
import com.jwgf.smarowindingmachine_unity.ui.CommonVar;
import com.jwgf.smarowindingmachine_unity.ui.SmaroWindingMachineActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

public class LengthAdjustAction implements MqttAction {
    private MachineParameterSharedPreference sp = MachineParameterSharedPreference.getInstance();
    private ArrayList<String> adjustList = new ArrayList<String>();

    @Override
    public void action(JSONObject object) {

        sp.setLengthAdjustRatio(Integer.valueOf(object.getString(InputKeys.VALUE)));
        sp.setLengthAdjustAccumulativeRatio(Integer.valueOf(object.getString(InputKeys.VALUE)));
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");// 设置你想要的格式
        String dateStr = df.format(Calendar.getInstance().getTime());
        sp.setLengthAdjustRatioTime(dateStr);

        int adjustRatio = Integer.valueOf(object.getString(InputKeys.VALUE));
        int groupNum = GroupMap.getInstance().getGroupCount();
        ArrayList<byte[]> cmdList = new ArrayList<byte[]>();
        cmdList.addAll(sp.getBroadcast());

        for (int i = 1; i <= groupNum; i++) {
            String s_pkg_len = sp.getValue(i, 0x24, 0);
            int pkg_len = (int) (Integer.parseInt(s_pkg_len) * (1 + adjustRatio / 10000f));
            sp.setValue(i, 0x24, 0x00, String.valueOf(pkg_len));
            float slip_coef = Float.parseFloat(sp.getValue(i, MachineParameterSharedPreference.SPINDLE_SLIP));
            float temp = pkg_len * CommonVar.LENGTH_TO_PULSE_FACTOR * slip_coef;
            int length_pulse = Math.round(temp);
            String s_pulse = String.valueOf(length_pulse);
            cmdList.addAll(sp.createCanCmd24(i, 0x24, 0x00, s_pulse));
//            String str = String.format(Locale.US, "组" + i + "调整长度：%1$d 调整量：%2$d 时间：%3$s",
//                    pkg_len, sp.getLengthAdjustRatio(), sp.getLengthAdjustRatioTime());
//            if (adjustList.size() > 10) {
//                adjustList.remove(0);
//            }
//            adjustList.add(str);
            sp.setValue("adjust_log", JSONObject.toJSONString(adjustList));
        }
        cmdList.addAll(sp.releaseBroadcast());
        SmaroWindingMachineActivity.canHandStack.putPriorityCmd(cmdList);

    }

}
